<?php

namespace App\Jobs;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Database\Eloquent\Model;
use App\Models\Sys as SysModel;
use App\Models\User as UserModel;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use App\Models\ThroughLog as LogModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class ThroughLogJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    private $data;
    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($data)
    {
        $this->data=$data;
    }

    /**
     * Execute the job.
     *
     * @return void
     */
    public function handle()
    {

        $this->sysModel=new SysModel();
        $this->userModel=new UserModel();
        $this->shareLogModel=new LogModel();
        $type=$this->data["type"];
        $typeValue=[
            "chick"=>0,
            "draw"=>1,
            "tree"=>2
        ];
        DB::beginTransaction();
        try {
            $log=$this->shareLogModel->where("uid",$this->data['uid'])->where("type",$typeValue[$type])->where("date",date("Y-m-d"))->count();
            $share_get_draw=$this->sysModel->get_Value("through_get_draw_time");
            $share_get_draw_limit=$this->sysModel->get_Value("through_limit");
            $tree_reward_limit=$this->sysModel->get_Value("tree_reward_limit");


            $user=UserModel::where("id",$this->data['uid'])->first();
            if ($user){
                $log="";
                if($type=="chick"&&$share_get_draw_limit>$log){
                    $user->increment("food",1);
                    $log="浏览房屋信息获取饲料1次";
                }

                if($type=="draw"&&$share_get_draw>$log){
                    $user->increment("draw_times",1);
                    $log="浏览项目信息获取抽奖次数1次";
                }

                if($type=="tree"&&$tree_reward_limit>$log){
                    $user->increment("tree",1);
                    $log="浏览项目获取浇水1次";
                }


                if($log){
                    $create=[
                        "uid"=>$this->data['uid'],
                        "content"=>"浏览房屋信息获取抽奖次数{$share_get_draw}次",
                        "date"=>date("Y-m-d"),
                        "type"=>$typeValue[$type]
                    ];
                }

                $this->shareLogModel->create($create);
            }


            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Log::error($exception->getMessage());
        }
    }
}
